# == Schema Information
# Schema version: 38
#
# Table name: posts
#
#  id           :integer(11)     not null, primary key
#  topic_id     :integer(11)
#  user_id      :integer(11)
#  content      :text
#  content_html :text
#  created_at   :datetime
#  updated_at   :datetime
#

class Post < ActiveRecord::Base
  belongs_to :topic, :counter_cache => true
  belongs_to :user
  
  validates_presence_of :content
  format_attribute :content
  
  after_save :update_topic_after_save
  
  def editable_by?(user)
    user!=:false && (user.id==user_id || user.is_admin? || self.topic.group.moderated_by?(user))
  end
  
  def self.archives
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = Post.find_by_sql(["select count(*) as count, #{date_func} from posts where created_at < ? group by year,month order by year asc,month asc",Time.now])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
  
  private
  def update_topic_after_save
    topic = self.topic
    topic.posts_count = Post.count(:id, :conditions => {:topic_id => topic.id})
    topic.replied_at = self.updated_at
    topic.replied_by_user = self.user
    topic.save!
  end
end
